package com.example.endusation.neo4j;

import org.neo4j.driver.Driver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.core.Neo4jClient;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class KnowledgeGraphService {


    private final Driver neo4jDriver;
    private final Neo4jClient neo4jClient;

    @Autowired
    public KnowledgeGraphService(Driver neo4jDriver) {
        this.neo4jDriver = neo4jDriver;
        this.neo4jClient = Neo4jClient.create(neo4jDriver);
    }


    // 查询某个概念的N层关联节点（如2层内的相关概念）
    public Collection<Map<String, Object>> queryConceptLayers(String conceptName, int depth) {
        // 关键修正：在 MATCH 后定义路径变量 p = (...)
        String cypher = String.format("""
    MATCH p = (c:Entity {name: $name})-[*1..%d]-(related)
    RETURN c.name AS source, 
           related.name AS target, 
           head([r in relationships(p) | r.type]) AS relation  // 取数组第一个元素
    """, depth);


        return neo4jClient.query(cypher)
                .bind(conceptName).to("name")
                .fetch().all();
    }

}

